/*
 * @Author: silence
 * @Date: 2023-03-13 10:22:38
 * @LastEditors: silence silence9685@163.com
 * @LastEditTime: 2023-06-19 09:14:44
 * @Description: 设备信息相关
 */

import 'dart:io';

import 'package:device_info_plus/device_info_plus.dart';
import 'package:flutter_keychain/flutter_keychain.dart';
import 'package:sil_utils_package/sil_utils_package.dart';

import '../../api/RequestParamsUtils.dart';

class DeviceInfo {
  /// 获取当前设备的唯一标识
  static Future<String> deviceUniqueId() async {
    final deviceInfoPlugin = DeviceInfoPlugin();

    String? deviceUnicode;
    String key = 'deviceUnicode';

    try {
      if (Platform.isIOS) {
        // String iOSUdId = androidIdByApp('NC');

        // 获取唯一码，因为重装应用之后，iOS设备的唯一标识会变，所以将获取的唯一标识，放入钥匙串中
        deviceUnicode = await FlutterKeychain.get(key: key);
        if (deviceUnicode == null) {
          final iosDeviceInfo = await deviceInfoPlugin.iosInfo;
          await FlutterKeychain.put(
              key: key, value: iosDeviceInfo.identifierForVendor!);
          deviceUnicode = iosDeviceInfo.identifierForVendor;
        }
      } else {
        // 鉴于android的开放性，不同厂商的可能不一样，使用自己生成唯一标识符
        deviceUnicode = await FlutterKeychain.get(key: key);
        if (deviceUnicode == null) {
          String androidId = androidIdByApp('NC');
          await FlutterKeychain.put(key: key, value: androidId);
          deviceUnicode = androidId;
        }
      }
    } catch (e) {
      print('web不做处理');
    } finally {
      SilLog.v("设备唯一码：" + deviceUnicode!);
      return deviceUnicode;
    }
  }

  static String androidIdByApp(String appName) {
    // 当前时间戳
    int timeStamp = SilTimeUtils.currentTimeMillis() ~/ 1000;
    print("timeStamp = $timeStamp");
    String androidId = generate_MD5("NC$timeStamp$appName");

    return androidId;
  }
}
